/* wx的调用接口公用方法*/
import { success } from './success';
import { start } from './start';
import { fail } from './fail';
import superagent from 'superagent';

/**
 * 后端渲染使用，在server端初始化时传入req类, 后端目前不需要有回调方法的触发。
 * @param req
 * @returns {function(*=, *=, *=, *=): function(*, *, *)}
 */
export default function serverFetch(req) {
    return (action, url, params, extra = {}) => (dispatch, store, next) => {
        dispatch(start(action, { params, fetchResult: {}, ...extra }));
        return new Promise((resolve) => {
            const request = superagent.post(url);
            if (params) {
                request.query(params);
            }
            if (req.get('cookie')) {
                request.set('cookie', req.get('cookie'));
            }
            request.send(params);
            request.withCredentials().end((err, { body: fetchResult } = {}) => {
                if (fetchResult && fetchResult.code > 0) {
                    resolve(success(action, { params, fetchResult, ...extra }));
                } else {
                    resolve(fail(action, { params, fetchResult: {}, ...extra }));
                }
            });
        }).then(a => dispatch(a));
    };
}
